<template>
    <el-container>
        <el-aside width="15%"></el-aside>
        <el-main>
            <el-alert title="以下功能可能会修改用户车位数据，请谨慎操作" type="warning" show-icon></el-alert>
            <el-divider></el-divider>
            <!--栅格-->
            <!--表格行数由parkingSpaceList长度决定，当length能被8整除则行数为length/8，否则为length/8 注意v-for遍历数字从1开-->
            <el-row :gutter="20"
                    v-for="i in parkingSpaceList.length % 8 == 0? parkingSpaceList.length/8+1 : parkingSpaceList.length/8+2" :key="i">
                <el-col v-for="(item, index) in parkingSpaceList.slice(8*(i-1), 8*(i-1) + 8)" :span="3" :key="index">
                    <!--一行显示8个单元格-->
                    <div class="grid-content" 
                    :class="item.locked? 'bg-red':item.id == selectId ? 'bg-yellow' : 'bg-green'"
                    v-on:click="selectSpace(item.id)">
                        编号：<strong>{{item.id}}</strong><br/>
                        <strong>{{statusType[item.status]}}</strong>
                    </div>
                </el-col>
            </el-row>

            <el-divider></el-divider>
            <el-row :gutter="20">
                <el-col :offset="3" :span="9">
                    <el-input v-model="selectId" type="number" clearable>
                        <template slot="prepend">目标车位编号</template>
                    </el-input>
                </el-col>
                <el-col :span="10" align="left">
                    <el-button type="warning" v-on:click="lock(selectId)" icon="el-icon-lock">锁定目标车位</el-button>
                    <el-button type="warning" v-on:click="unlock(selectId)" icon="el-icon-unlock">解锁目标车位</el-button>
                </el-col>
            </el-row>
            <el-divider></el-divider>
            <el-button type="danger" v-on:click="lockAll" icon="el-icon-lock">锁定所有车位</el-button>
            <el-button type="danger" v-on:click="unlockAll" icon="el-icon-unlock">解锁所有车位</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="primary" v-on:click="exit">退出登录</el-button>
        </el-main>
        <el-aside width="15%"></el-aside>
    </el-container>
</template>

<script>
import axios from 'axios'
export default {
    name: 'Admin',
    data() {
        return {
            id: null,
            selectId: null,
            statusType: ['空闲', '占用', '被预定', '管理员锁定'],
            parkingSpaceList: []
        }
    },
    methods: {
        findAll () {
            var that = this;
            axios.get("/park").then(
                function (response) {
                    that.parkingSpaceList = response.data;
                },
                function (err) {
                    console.log(err);
                }
            );
        },
        selectSpace(id) {
            // if (this.parkingSpaceList[id - 1].locked) {
            //     this.showMessage('warning', '该车位已被占用，不能选择！');
            //     return;
            // } else if (this.parkingSpaceList[id - 1].status == 2) {
            //     this.showMessage('warning', '该车位已被预约，不能选择！');
            //     return;
            // }
            if (id == this.selectId) {
                this.selectId = null;//取消
                this.selectMsg = "请选择要控制的车位";
            } else {
                this.selectId = id;
                this.selectMsg = "您已选择预约" + id + "号车位，请点击“锁定/解锁”车位按钮。";
            }
        },
        lock (id) {
            if (id == null || id == "") {
                this.showMessage('warning', "请输入id号");
                return;
            }
            var that = this;
            axios({
                method: "post",
                url: "/admin/lock",
                params: {id: id}
            }).then(function (response) {
                that.showMessage('info', response.data.msg);
            }, function (err) {
                console.log(err);
            });
        },
        unlock (id) {
            if (id == null || id == "") {
                this.showMessage('warning', "请输入id号");
                return;
            }
            var that = this;
            axios({
                method: "post",
                url: "/admin/unlock",
                params: {id: id}
            }).then(function (response) {
                that.showMessage('info', response.data.msg);
            }, function (err) {
                console.log(err);
            });
        },
        lockAll () {
            var that = this;
            axios({
                method: "post",
                url: "/admin/lockAll",
            }).then(function (response) {
                that.showMessage('info', response.data.msg);
            }, function (err) {
                console.log(err);
            });
        },
        unlockAll () {
            var that = this;
            axios({
                method: "post",
                url: "/admin/unlockAll",
            }).then(function (response) {
                that.showMessage('info', response.data.msg);
            }, function (err) {
                console.log(err);
            });
        },
        exit () {
            axios.get("/admin/exit").then((response) => {
                if (response.data.flag) {
                    this.$router.replace("/login");
                } else {
                    this.showMessage('warning', response.data.msg);
                }
            }, (err)=> {
                console.warn(err);
            });
        },
        showMessage (type, message) {
            this.$message({message: message, type: type});
        }
    },
    mounted() {
        this.findAll()

        //使用websocket显示实时车位信息
        var ip_addr = document.location.hostname;//服务器ip地址
        var websocket = null;
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://" + ip_addr + ":8080/ws/park");
            this.$websocket = websocket
        } else {
            alert("浏览器不支持websocket");
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            console.log("WebSocket连接发生错误");
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            console.log("WebSocket连接成功");
        }

        //接收到消息的回调方法
        websocket.onmessage = (event) => {
            //这里用箭头函数，this才是vm
            console.log('WebSocket收到推送数据', event.data);
            var jsonObj = JSON.parse(event.data);//把接收的json字符串转为对象
            this.parkingSpaceList.splice(jsonObj.id - 1, 1, jsonObj);//修改数组值要用splice，这里表示将索引为1开始的一个元素修修改为response.data
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            console.log("WebSocket连接关闭");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        // window.onbeforeunload = function () {
        //     websocket.close();
        // }

        //发送消息
        // function send() {
        //     var message = document.getElementById('text').value;
        //     websocket.send(message);
        // }
    },
    beforeDestroy() {
        //销毁组件时关闭websocket连接
        this.$websocket.close()
    }
}
</script>

<style scoped>
    .el-aside {
        background-color: whitesmoke;
        color: #333;
        text-align: center;
        line-height: 200px;
    }

    .el-main {
        background-color: #E9EEF3;
        color: #333;
        text-align: center;
        line-height: 60px;
        padding-top: 0px;
        padding-bottom: 0px;
        overflow: hidden;
    }

    body > .el-container {
        margin-bottom: 40px;
    }

    .el-container:nth-child(5) .el-aside,
    .el-container:nth-child(6) .el-aside {
        line-height: 260px;
    }

    .el-container:nth-child(7) .el-aside {
        line-height: 320px;
    }

    /**/
    .el-row {
        margin-bottom: 20px;

    /* &
    :last-child {
        margin-bottom: 0;
    } */

    }
    .el-col {
        border-radius: 4px;
    }

    .bg-purple-dark {
        background: #99a9bf;
    }

    .bg-purple {
        background: #d3dce6;
    }

    .bg-red {
        background: red;
    }

    .bg-green {
        background: green;
    }

    .bg-yellow {
        background: coral;
    }

    .bg-purple-light {
        background: #e5e9f2;
    }

    .grid-content {
        height: 150px;
        border-radius: 4px;
        min-height: 36px;
    }

    .row-bg {
        padding: 10px 0;
        background-color: #f9fafc;
    }
</style>